package com.ruoyi.shenji.utils;

import java.sql.Time;
import java.util.*;

public class GetMysqlSqlUtil {
    public static String getDropSql(String tableName) {
        return "DROP TABLE IF EXISTS " + tableName + ";";
    }

    public static String getSelectSql(String tableName, String columnNames, Map<String,Object> conditions) {
        // 检查输入的有效性
        if (tableName == null || tableName.isEmpty()) {
            throw new IllegalArgumentException("Invalid table name");
        }
        if (columnNames == null || columnNames.isEmpty()) {
            throw new IllegalArgumentException("Column names list cannot be empty");
        }

        // 构建WHERE子句（如果conditions非空）
        String whereClause = "";
        StringBuilder sb = new StringBuilder(" WHERE ");
        if (conditions != null && !conditions.isEmpty()) {
            boolean isFirst = true;
            for (Map.Entry<String, Object> entry : conditions.entrySet()) {
                if (isFirst) {
                    isFirst = false;
                } else {
                    sb.append(" AND ");
                }
                sb.append(entry.getKey()).append(" = "+entry.getValue());
            }
            whereClause = sb.toString();
        }

        return "SELECT " + columnNames + " FROM " + tableName + whereClause;
    }
    public static String getCreateSql(LinkedHashMap<String, Object> map,String tableName) {
        if (map == null || map.isEmpty()) {
            System.out.println("Map is empty or null.");
            return "erro";
        }

        if (tableName == null || tableName.isEmpty()) {
            System.out.println("Table name is missing in the map.");
            return "erro";
        }

        StringJoiner joiner = new StringJoiner(",\n");

        // 确保id字段始终位于SQL语句的开头
        joiner.add("id INT AUTO_INCREMENT PRIMARY KEY");

        for (Map.Entry<String, Object> entry : map.entrySet()) {
            String fieldName = entry.getKey();
            Object value = entry.getValue();
            String fieldType = getValueType(value);
            String fieldDefinition = String.format("%s %s", fieldName, fieldType);
            joiner.add(fieldDefinition);
        }

        // 生成创建表的 MySQL 语句
        String createTableSQL = String.format("CREATE TABLE IF NOT EXISTS %s (\n%s\n);", tableName, joiner);
        System.out.println("Generated MySQL:\n" + createTableSQL);
        return createTableSQL;

    }

    public static String getInsertSql (List<LinkedHashMap<String,Object>> dataList,String tableName){


        StringBuilder sqlBuilder = new StringBuilder("INSERT INTO ")
                .append(tableName)
                .append(" (");

        // 构建插入语句的列部分
        Set<String> columnNames = dataList.get(0).keySet();
        for (String columnName : columnNames) {
            sqlBuilder.append(columnName).append(", ");
        }
        sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length()); // 移除最后的逗号和空格
        sqlBuilder.append(") VALUES ");

        // 构建插入语句的值部分
        for (Map<String, Object> data : dataList) {
            sqlBuilder.append("(");
            for (Object value : data.values()) {
                if (value instanceof String) {
                    if("*".equals(value)){

                    }
                    sqlBuilder.append("'").append(value).append("', ");
                } else {
                    sqlBuilder.append(value).append(", ");
                }
            }
            sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length()); // 移除最后的逗号和空格
            sqlBuilder.append("), ");
        }
        sqlBuilder.delete(sqlBuilder.length() - 2, sqlBuilder.length()); // 移除最后的逗号和空格
        return sqlBuilder.toString();
    }

    public static String getUpdateSql(String tableName, Map<String, Object> fieldValues) {
        StringBuilder sql = new StringBuilder();
        sql.append("UPDATE ").append(tableName).append(" SET ");

        boolean firstField = true;
        for (Map.Entry<String, Object> entry : fieldValues.entrySet()) {
            if (!firstField || !entry.getKey().equals("id")) { // 不处理where条件中的键
                if (!firstField) {
                    sql.append(", ");
                }
                sql.append(entry.getKey()).append(" = "+entry.getValue());
                firstField = false;
            } else {
                // 保存主键值以供构建WHERE条件
                Object primaryKeyValue = entry.getValue();
            }
        }

        sql.append(" WHERE id = "+fieldValues.get("id")); // 假设主键列名为primary_key_column

        return sql.toString();
    }

    public static String getDeleteSql(String tableName, List<Integer> ids) {
        if (ids.isEmpty()) {
            return "";
        }

        StringBuilder sqlBuilder = new StringBuilder("DELETE FROM ").append(tableName).append(" WHERE id IN (");

        for (int i = 0; i < ids.size(); i++) {
            Integer id = ids.get(i);
            sqlBuilder.append(id);

            if (i < ids.size() - 1) {
                sqlBuilder.append(", ");
            }
        }

        sqlBuilder.append(")");

        return sqlBuilder.toString();
    }
    private static String getValueType(Object value) {
        if (value instanceof Integer) {
            return "INT";
        } else if (value instanceof Long) {
            return "BIGINT";
        } else if (value instanceof Double || value instanceof Float) {
            return "FLOAT";
        } else if (value instanceof Boolean) {
            return "BOOLEAN";
        } else if (value instanceof String) {
            return "VARCHAR(255)";
        } else if (value instanceof Date) {
            return "DATE";
        } else if (value instanceof Time) {
            return "TIME";
        }
//        else if (value instanceof Timestamp) {
//            return "TIMESTAMP";
//        } else if (value instanceof BigDecimal) {
//            return "DECIMAL(10,2)"; // 可根据实际需求进行参数设置
//        } else if (value instanceof Blob) {
//            return "BLOB";
//        } else if (value instanceof Clob) {
//            return "CLOB";
//        }
        else {
            return "OTHER";
        }
    }

}
